package vn.edu.hut.soict.alignment;

import java.util.HashMap;
import java.util.List;

import vn.edu.hut.soict.translate.utils.StringUtils;

public class BiDirectionalTokenAlignment extends BiDirectionalAlignment {

	public BiDirectionalTokenAlignment(String source, String destination, String syllableAlinmentCode) {
		this(new BiDirectionalSyllableAlignment(source, destination, syllableAlinmentCode));
	}

	public BiDirectionalTokenAlignment(BiDirectionalSyllableAlignment preAlignment) {
		this.source = tokenizeSource(preAlignment.getSource());
		this.destination = preAlignment.getDestination();
		parseAlignment(preAlignment);
		reverseAlignment();
	}

	private List<String> tokenizeSource(List<String> source) {
		StringBuilder sb = new StringBuilder();
		for (String s : source) {
			sb.append(s).append(" ");
		}
		return StringUtils.splitIntoToken(sb.toString().trim());
	}

	private void parseAlignment(BiDirectionalSyllableAlignment preAlignment) {
		alignment = new HashMap<Integer, List<Integer>>();
		int syllableCount = 0;
		for (int sourceIndex = 0; sourceIndex < source.size(); sourceIndex++) {
			List<Integer> destinationList = null;
			int count = StringUtils.syllableCount(source.get(sourceIndex));
			for (int j = syllableCount; j < syllableCount + count; j++) {
				List<Integer> list = preAlignment.destinationIndexesAlignWith(j);
				if (destinationList == null) {
					destinationList = list;
				}
				else if (destinationList != null && !destinationList.equals(list)) {
//					try {
//						throw new Exception("Parse error: Alignment of token " + sourceIndex + " is error.");
//					}
//					catch (Exception e) {
//						e.printStackTrace();
//					}
					destinationList.addAll(list);
				}
			}
			alignment.put(sourceIndex, destinationList);
			syllableCount += count;
		}
		List<Integer> destinationList = preAlignment.destinationIndexesAlignWith(null);
		if (destinationList != null) {
			alignment.put(null, destinationList);
		}
	}
}
